from django.shortcuts import render,HttpResponse
from user.models import *
# Create your views here.
def index_handler(request):
    users = User.objects.all()
    return render(request,'index.html',context={'users':users})


def alter_handler(request,id):
    user = User.objects.get(id=id)
    if request.method=='GET':
        return render(request,'alter.html',{'user':user})
    else:
        user.username = request.POST.get("username")
        user.password = request.POST.get("password")
        user.age = request.POST.get("age")
        user.email = request.POST.get("email")
        try:
            user.save()
            return render(request,'result.html',{'message':'用户修改成功'})
        except Ellipsis as e:
            print(e)
            return render(request,'result.html',{'message':'用户修改失败'})


def del_handler(request,id):
    try:
        User.objects.get(id=id).delete()
        return render(request,'result.html',{'message':'用户删除成功'})
    except Ellipsis as e:
        print(e)
        return render(request, 'result.html', {'message': '用户删除失败'})


def add_handler(request):
    if request.method=='GET':
        return render(request,'add.html')
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        age = request.POST.get('age')
        email = request.POST.get('email')
        try:
            User(username=username,password=password,age=age,email=email).save()
            return render(request,'result.html',{'message':'新增用户成功'})
        except Ellipsis as e:
            print(e)
            return render(request,'result.html',{'message':'新增用户失败'})
